const express = require('express');

const db = require('../db')

const router =express.Router();

// --------------------------------------------------查看我的收藏------------------------------------------
router.get('/get_collect',(req,res)=>{
    const {limit,page}=req.body;
    const {user_id}=req.user
    let sql;
    sql=`select * from collect left outer join car_info on collect.car_id=car_info.car_id  where user_id=${user_id}`
    if (limit && page) {
        let start=` limit ${(page-1)*limit},${limit}`
        sql +=start;
    }
    db(sql, (err,data)=>{
        if (err) {
            res.send({
                code:-1,
                msg:err.sqlMessage,
            })
            throw err;
        }
        db(`select count(1) as count from collect where user_id=${user_id}`,(err,reslut)=>{
            if (err) {
                res.send({
                    code:-1,
                    msg:err.sqlMessage,
                })
                throw err;
            }
            res.send({
                code:1,
                count:reslut[0].count,
                data
            })
        })
    })
})

// --------------------------------------------------添加/取消收藏------------------------------------------
router.post('/set_collect',(req,res)=>{
    const {car_id}=req.body;
    const {user_id}=req.user;
    db(`select * from collect where user_id=${user_id} && car_id=${car_id}`,(err,data)=>{
        // 判断是否含有此条收藏，有的话取消收藏，无的话添加收藏
        if(data.length){
            db(`delete from collect where collect_id = ${data[0].collect_id}`,err=>{
                if (err) {
                    res.send({
                        code:-1,
                        msg:err.sqlMessage,
                    })
                    throw err;
                }
                res.send({
                    code:1,
                    msg:'取消收藏！'
                })
            })
        }else{
            db(`insert into collect(user_id,car_id) values (${user_id},${car_id})`,(err)=>{
                if (err) {
                    res.send({
                        code:-1,
                        msg:err.sqlMessage,
                    })
                    throw err;
                }
                res.send({
                    code:1,
                    msg:'收藏成功！'
                })
            })
        }
    })
})






module.exports=router